﻿using System;
using System.Collections.Generic;
using System.Linq;
using Missbot.Common;
using Missbot.Core.Base;
using Missbot.Core.Cache;
using Dolany.UtilityTool;
using JetBrains.Annotations;
using Missbot.AIModule.Base;
using Missbot.Model.MsgInfos;
using Newtonsoft.Json;

namespace Missbot.AIModule.SingleCommand.Fortune
{
    [UsedImplicitly]
    public class FortuneMod : IAIModule, IDataMgr
    {
        public override string Name => "运势";

        private List<FortuneItem> FortuneItemList { get; set; } = new();
        private List<TarotFortune> TarotFortuneList { get; set; } = new();

        public void RefreshData()
        {
            FortuneItemList = FortuneItemDA.GetAll();
            TarotFortuneList = TarotFortuneDA.GetAll();
        }

        [ModuleEnter(Command = ".luck 祈愿运势 。luck", Description = "获取每天运势")]
        public bool RandomFortune(InboxSession session)
        {
            var response = PersonCacheRecordDA.Get(session.User.ID, "RandomFortune");

            if (string.IsNullOrEmpty(response.Value))
            {
                var randFor = GetRandomFortune();
                var rf = new RandomFortuneCache
                {
                    UserID = session.User.ID,
                    FortuneValue = randFor,
                    BlessName = string.Empty,
                    BlessValue = 0
                };
                RandBless(rf);
                ShowRandFortune(session, rf);

                response.Value = JsonConvert.SerializeObject(rf);
                response.ExpiryTime = CommonUtil.UntilTommorow();
                response.Update();
            }
            else
            {
                ShowRandFortune(session, JsonConvert.DeserializeObject<RandomFortuneCache>(response.Value));
            }

            return true;
        }

        private void RandBless(RandomFortuneCache rf)
        {
            if (rf.FortuneValue >= 50 || Rander.RandInt(100) > 20)
            {
                return;
            }

            var item = FortuneItemList.RandElement();
            rf.BlessName = item.Name;
            rf.BlessValue = item.Value;
        }

        private static int GetRandomFortune()
        {
            return Rander.RandInt(101);
        }

        private static void ShowRandFortune(InboxSession session, RandomFortuneCache rf)
        {
            var buffer = new OutputBuffer(session);
            switch (rf.BlessValue)
            {
                case > 0:
                {
                    rf.FortuneValue += rf.BlessValue;
                    rf.FortuneValue = rf.FortuneValue > 100 ? 100 : rf.FortuneValue;
                    buffer.Add($"恭喜你受到了 {rf.BlessName} 的祝福");
                    buffer.Add($"你今天的运势是：{rf.FortuneValue}%({rf.BlessValue}↑)");
                    break;
                }
                case < 0:
                {
                    rf.FortuneValue += rf.BlessValue;
                    rf.FortuneValue = rf.FortuneValue < 0 ? 0 : rf.FortuneValue;
                    buffer.Add($"哎呀呀，你受到了 {rf.BlessName} 的诅咒");
                    buffer.Add($"你今天的运势是：{rf.FortuneValue}%({Math.Abs(rf.BlessValue)}↓)");
                    break;
                }
                default:
                {
                    buffer.Add($"你今天的运势是：{rf.FortuneValue}%");
                    break;
                }
            }

            buffer.Add(string.Join("", Enumerable.Repeat("|", rf.FortuneValue)));
            buffer.Send();
        }

        [ModuleEnter(Command = "星座运势", Description = "获取星座运势")]
        public bool StarFortune(InboxSession session)
        {
            var jr = new FortuneRequestor(session);
            jr.Work();
            return true;
        }

        [ModuleEnter(Command = ".zhan 塔罗牌占卜 。zhan", Description = "获取每日塔罗牌占卜")]
        public bool DailyTarotFortune(InboxSession session)
        {
            var cache = PersonCacheRecordDA.Get(session.User.ID, "TarotFortune");

            TarotCacheModel fortune;
            if (string.IsNullOrEmpty(cache.Value))
            {
                fortune = GetRandTarotFortune();
                cache.Value = JsonConvert.SerializeObject(fortune);
                cache.ExpiryTime = CommonUtil.UntilTommorow();
                cache.Update();
            }
            else
            {
                fortune = JsonConvert.DeserializeObject<TarotCacheModel>(cache.Value);
            }

            SendTarotFortune(session, fortune);
            return true;
        }

        private void SendTarotFortune(InboxSession session, TarotCacheModel data)
        {
            if (data == null)
            {
                return;
            }

            var ptr = data.IsPos ? "正位" : "逆位";
            var buffer = new OutputBuffer(session);
            buffer.AddFile(data.FileID);
            buffer.Add($"牌名：{ptr}{data.CardName}");
            buffer.Add($"{ptr}解释：");

            var model = TarotFortuneList.First(p => p.Name == data.CardName);
            buffer.Add(data.IsPos ? model.Positive : model.Passive);
            buffer.Send();
        }

        private TarotCacheModel GetRandTarotFortune()
        {
            var randTarot = TarotFortuneList.RandElement();
            return new TarotCacheModel
            {
                CardName = randTarot.Name,
                IsPos = Rander.RandBool(),
                FileID = randTarot.PicIDs.RandElement()
            };
        }

        [ModuleEnter(Command = "圣光祝福",
                     Description = "祝福一个成员，让其随机运势增加80%（最高100%），当日有效",
                     DailyLimit = 5,
                     AuthLvl = AuthorityLevel.Owner,
                     SyntaxHint = "[@用户名]",
                     ChannelType = ChannelType.Messaging)]
        public bool HolyLight(InboxSession session, InstanceUser aimUser)
        {
            Bless(aimUser.ID, "圣光祝福", 80);
            session.SendBack("祝福成功！");
            return true;
        }

        private static void Bless(string UserID, string BlessName, int BlessValue)
        {
            var response = PersonCacheRecordDA.Get(UserID, "RandomFortune");

            var model = string.IsNullOrEmpty(response.Value) ? null : JsonConvert.DeserializeObject<RandomFortuneCache>(response.Value);
            if (model == null)
            {
                var randFor = GetRandomFortune();
                var rf = new RandomFortuneCache
                {
                    UserID = UserID,
                    FortuneValue = randFor,
                    BlessName = BlessName,
                    BlessValue = BlessValue
                };
                response.Value = JsonConvert.SerializeObject(rf);
                response.ExpiryTime = CommonUtil.UntilTommorow();
                response.Update();
            }
            else
            {
                model.BlessName = BlessName;
                model.BlessValue = BlessValue;

                response.Value = JsonConvert.SerializeObject(model);
                response.ExpiryTime = CommonUtil.UntilTommorow();
                response.Update();
            }
        }

        [ModuleEnter(Command = "创世神祝福",
                     Description = "祝福一个成员，让其随机运势增加100%，当日有效",
                     DailyLimit = 3,
                     AuthLvl = AuthorityLevel.Owner,
                     SyntaxHint = "[@用户名]",
                     ChannelType = ChannelType.Messaging)]
        public bool CreatorBless(InboxSession session, InstanceUser aimUser)
        {
            Bless(aimUser.ID, "创世神", 100);
            session.SendBack("祝福成功！");
            return true;
        }

        [ModuleEnter(Command = "暗夜诅咒",
                     Description = "诅咒一个成员，让其随机运势减少若干点（最低0%），当日有效",
                     DailyLimit = 3,
                     AuthLvl = AuthorityLevel.Owner,
                     SyntaxHint = "[@用户名]",
                     ChannelType = ChannelType.Messaging)]
        public bool Darkness(InboxSession session, InstanceUser aimUser)
        {
            Bless(aimUser.ID, "暗夜诅咒", -GetRandomFortune());
            session.SendBack("诅咒成功！");
            return true;
        }
    }
}